"""
Kubernetes资源健康检查和依赖分析API
"""
from typing import Dict, List, Optional, Union, Any, Tuple
import logging
from .core.health_checker import HealthChecker
from .core.dependency_analyzer import ResourceDependencyAnalyzer
from .core.report_formatters import ReportFormatterFactory
from .config.manager import ConfigManager
from .core.resource_utils import (
    ResourceValidator,
    ResourceConverter,
    ResourceComparer,
    ResourceMerger
)

import copy
from dataclasses import dataclass
import yaml

logger = logging.getLogger(__name__)

@dataclass
class AnalysisResult:
    """分析结果"""
    health_status: Dict[str, Any]
    dependencies: Dict[str, Any]
    validation_results: Dict[str, Any]
    comparison_results: Dict[str, Any]
    merge_results: Dict[str, Any]

class K8sResourceAnalyzer:
    """Kubernetes资源分析器主类"""
    
    def __init__(self, config_path: Optional[str] = None):
        """
        初始化分析器
        
        Args:
            config_path: 配置文件路径，如果为None则使用默认配置
        """
        self.config = ConfigManager(config_path) if config_path else ConfigManager()
        self.health_checker = HealthChecker(self.config)
        self.dependency_analyzer = ResourceDependencyAnalyzer()
        self.report_formatter = ReportFormatterFactory.create_formatter_chain(
            self.config.get('report.template_dir')
        )
        
        # 初始化资源工具
        self.validator = ResourceValidator()
        self.converter = ResourceConverter()
        self.comparer = ResourceComparer()
        self.merger = ResourceMerger()
        
        if config_path:
            self._load_config(config_path)
    
    def add_resource(self, resource: Dict[str, Any]) -> bool:
        """
        添加Kubernetes资源
        
        Args:
            resource: Kubernetes资源定义
            
        Returns:
            bool: 是否添加成功
        """
        try:
            # 验证资源
            validation_result = self.validator.validate(resource)
            if not validation_result.is_valid:
                logger.error(f"资源验证失败: {validation_result.errors}")
                return False
            
            # 添加到健康检查器
            self.health_checker.add_resource(resource)
            
            # 添加到依赖分析器
            self.dependency_analyzer.add_resource(resource)
            
            return True
            
        except Exception as e:
            logger.error(f"添加资源失败: {str(e)}")
            return False
    
    def add_resources(self, resources: List[Dict[str, Any]]) -> None:
        """
        批量添加Kubernetes资源
        
        Args:
            resources: Kubernetes资源定义列表
        """
        for resource in resources:
            self.add_resource(resource)
    
    def check_health(self) -> Dict[str, Any]:
        """
        执行健康检查
        
        Returns:
            健康检查结果
        """
        return self.health_checker.check_resources()
    
    def analyze_dependencies(self) -> Dict[str, Any]:
        """
        分析资源依赖关系
        
        Returns:
            依赖分析结果
        """
        return self.dependency_analyzer.analyze_dependencies()
    
    def export_report(
        self,
        data: Dict[str, Any],
        output_path: str,
        format_type: str = 'yaml'
    ) -> bool:
        """
        导出报告
        
        Args:
            data: 要导出的数据
            output_path: 输出路径
            format_type: 输出格式
            
        Returns:
            是否成功导出
        """
        return self.report_formatter.format(data, output_path)
    
    def export_health_report(
        self,
        output_path: str,
        format_type: str = 'yaml'
    ) -> bool:
        """
        导出健康检查报告
        
        Args:
            output_path: 输出路径
            format_type: 输出格式
            
        Returns:
            是否成功导出
        """
        health_data = self.check_health()
        return self.export_report(health_data, output_path, format_type)
    
    def export_dependency_report(
        self,
        output_path: str,
        format_type: str = 'yaml'
    ) -> bool:
        """
        导出依赖分析报告
        
        Args:
            output_path: 输出路径
            format_type: 输出格式
            
        Returns:
            是否成功导出
        """
        dependency_data = self.analyze_dependencies()
        return self.export_report(dependency_data, output_path, format_type)
    
    def get_health_status(self) -> Dict[str, Any]:
        """
        获取健康状态摘要
        
        Returns:
            健康状态摘要
        """
        return self.health_checker.get_health_status()
    
    def get_dependency_graph(self) -> Dict[str, Any]:
        """
        获取依赖关系图
        
        Returns:
            依赖关系图
        """
        return self.dependency_analyzer.get_dependency_graph()
    
    def get_resource_details(self, resource_id: str) -> Optional[Dict[str, Any]]:
        """
        获取资源详细信息
        
        Args:
            resource_id: 资源ID
            
        Returns:
            资源详细信息，如果不存在则返回None
        """
        return self.health_checker.get_resource_details(resource_id)
    
    def get_dependent_resources(self, resource_id: str) -> List[str]:
        """
        获取依赖指定资源的资源列表
        
        Args:
            resource_id: 资源ID
            
        Returns:
            依赖该资源的资源ID列表
        """
        return self.dependency_analyzer.get_dependent_resources(resource_id)
    
    def get_resource_dependencies(self, resource_id: str) -> List[str]:
        """
        获取指定资源依赖的资源列表
        
        Args:
            resource_id: 资源ID
            
        Returns:
            该资源依赖的资源ID列表
        """
        return self.dependency_analyzer.get_resource_dependencies(resource_id)
    
    def validate_resource(self, resource: Dict[str, Any]) -> Dict[str, Any]:
        """
        验证资源定义
        
        Args:
            resource: 资源定义
            
        Returns:
            验证结果
        """
        is_valid, errors = self.validator.validate(resource)
        return {
            "valid": is_valid,
            "errors": errors
        }
    
    def convert_resource(
        self,
        resource: Union[Dict[str, Any], str],
        target_format: str
    ) -> Union[Dict[str, Any], str]:
        """
        转换资源格式
        
        Args:
            resource: 资源定义或字符串
            target_format: 目标格式
            
        Returns:
            转换后的资源
        """
        return self.converter.convert(resource, target_format)
    
    def compare_resources(
        self,
        resource1: Dict[str, Any],
        resource2: Dict[str, Any],
        ignore_paths: Optional[List[str]] = None
    ) -> Dict[str, Any]:
        """
        比较两个资源
        
        Args:
            resource1: 第一个资源
            resource2: 第二个资源
            ignore_paths: 要忽略的路径列表
            
        Returns:
            差异信息
        """
        return self.comparer.compare(resource1, resource2, ignore_paths)
    
    def merge_resources(
        self,
        resources: List[Dict[str, Any]],
        strategy: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        合并多个资源
        
        Args:
            resources: 资源列表
            strategy: 合并策略
            
        Returns:
            合并后的资源
        """
        return self.merger.merge(resources, strategy)
    
    def merge_resources_with_strategy(
        self,
        resources: List[Dict[str, Any]],
        strategy_config: Dict[str, str]
    ) -> Dict[str, Any]:
        """
        使用自定义策略合并资源
        
        Args:
            resources: 资源列表
            strategy_config: 策略配置
            
        Returns:
            合并后的资源
        """
        return self.merger.merge_with_strategy(resources, strategy_config)
    
    def validate_and_convert(
        self,
        resource: Union[Dict[str, Any], str],
        target_format: str
    ) -> Tuple[bool, Union[Dict[str, Any], str], List[str]]:
        """
        验证并转换资源
        
        Args:
            resource: 资源定义或字符串
            target_format: 目标格式
            
        Returns:
            (是否有效, 转换后的资源, 错误消息列表)
        """
        # 如果输入是字符串，先转换为字典
        if isinstance(resource, str):
            try:
                resource = self.converter.convert(resource, "dict")
            except Exception as e:
                return False, resource, [str(e)]
        
        # 验证资源
        is_valid, errors = self.validator.validate(resource)
        if not is_valid:
            return False, resource, errors
        
        # 转换资源
        try:
            converted = self.converter.convert(resource, target_format)
            return True, converted, []
        except Exception as e:
            return False, resource, [str(e)]
    
    def compare_and_merge(
        self,
        resources: List[Dict[str, Any]],
        base_resource: Optional[Dict[str, Any]] = None
    ) -> Dict[str, Any]:
        """
        比较并合并资源
        
        Args:
            resources: 资源列表
            base_resource: 基准资源
            
        Returns:
            合并结果
        """
        if not resources:
            return {}
        
        # 如果没有指定基准资源，使用第一个资源
        base = base_resource or resources[0]
        
        # 比较所有资源与基准资源的差异
        diffs = []
        for resource in resources:
            if resource != base:
                diff = self.comparer.compare(base, resource)
                diffs.append({
                    "resource": resource,
                    "diff": diff
                })
        
        # 根据差异合并资源
        result = copy.deepcopy(base)
        for diff_info in diffs:
            self.merger._merge_dict(result, diff_info["resource"])
        
        return {
            "base": base,
            "differences": diffs,
            "merged": result
        }
    
    def get_available_formats(self) -> List[str]:
        """
        获取可用的报告格式
        
        Returns:
            可用格式列表
        """
        return self.config.get('report.formats')
    
    def get_config(self) -> Dict[str, Any]:
        """
        获取当前配置
        
        Returns:
            配置信息
        """
        return self.config.get_all()
    
    def update_config(self, config: Dict[str, Any]) -> None:
        """
        更新配置
        
        Args:
            config: 新的配置
        """
        self.config.update(config)
        # 重新初始化组件
        self.health_checker = HealthChecker(self.config)
        self.report_formatter = ReportFormatterFactory.create_formatter_chain(
            self.config.get('report.template_dir')
        ) 
    
    def analyze_resources(self) -> AnalysisResult:
        """
        分析所有资源
        
        Returns:
            AnalysisResult: 分析结果
        """
        return AnalysisResult(
            health_status=self.check_health(),
            dependencies=self.analyze_dependencies(),
            validation_results={},  # 待实现
            comparison_results={},  # 待实现
            merge_results={}  # 待实现
        )
    
    def _load_config(self, config_path: str):
        """加载配置"""
        try:
            with open(config_path, "r", encoding="utf-8") as f:
                config = yaml.safe_load(f)
            self.update_config(config)
            
        except Exception as e:
            logger.error(f"加载配置失败: {str(e)}")
            raise 